<template>
  <BasicModal @register="registerModal" width="1200" title="自定义按钮" defaultFullscreen @cancel="onCancel">
    <template #footer>
      <a-button @click="onCancel">关闭</a-button>
      <div v-if="aiTestMode" style="float: left">
        <a-button @click="onGenButtons">生成测试数据</a-button>
      </div>
    </template>
    <template #default>
      <BasicTable @register="registerTable" :rowSelection="rowSelection">
        <template #tableTitle>
          <a-button @click="onAdd" type="primary" preIcon="ant-design:plus">新增</a-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="onBatchDelete"> <a-icon type="delete" />删除 </a-menu-item>
              </a-menu>
            </template>
            <template #default>
              <a-button style="margin-left: 8px" @click="onCancel">批量操作<a-icon type="down" /></a-button>
            </template>
          </a-dropdown>
        </template>
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
        </template>
      </BasicTable>
      <BasicModal v-bind="formModalProps">
        <a-spin :spinning="formModalProps.confirmLoading">
          <BasicForm @register="registerForm" />
        </a-spin>
      </BasicModal>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, computed, nextTick } from 'vue';
  import { useOnlineTest } from '../../use/useOnlineTest.js';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { defHttp } from '/@/utils/http/axios';

  const list = (code, params) => defHttp.get({ url: '/api-online/online/cgform/button/list/' + code, params });
  function doBatchDelete(idList) {
    return defHttp.delete(
      {
        url: '/api-online/online/cgform/button/deleteBatch',
        params: {
          ids: idList.join(','),
        },
      },
      { joinParamsToUrl: true }
    );
  }
  const saveOrUpdate = (params, isUpdate) => {
    if (isUpdate) {
      return defHttp.put({ url: '/api-online/online/cgform/button/edit', params });
    } else {
      return defHttp.post({ url: '/api-online/online/cgform/button/add', params });
    }
  };
  const columns = [
    { title: '按钮编码', align: 'center', dataIndex: 'buttonCode' },
    { title: '按钮名称', align: 'center', dataIndex: 'buttonName' },
    {
      title: '按钮样式',
      align: 'center',
      dataIndex: 'buttonStyle',
      customRender({ text, record }) {
        if (text === 'form') {
          let p = record.optPosition;
          return text + '(' + (p == '2' ? '底部' : '侧面') + ')';
        } else {
          return text;
        }
      },
    },
    { title: '按钮类型', align: 'center', dataIndex: 'optType' },
    { title: '排序', align: 'center', dataIndex: 'orderNum' },
    { title: '按钮图标', align: 'center', dataIndex: 'buttonIcon' },
    { title: '表达式', align: 'center', dataIndex: 'exp' },
    {
      title: '按钮状态',
      align: 'center',
      dataIndex: 'buttonStatus',
      customRender({ text }) {
        if (text == 1) {
          return '激活';
        } else {
          return '未激活';
        }
      },
    },
  ];
  const formSchemas = [
    {
      label: '按钮编码',
      field: 'buttonCode',
      component: 'Input',
      required: true,
    },
    {
      label: '按钮名称',
      field: 'buttonName',
      component: 'Input',
      required: true,
    },
    {
      label: '按钮样式',
      field: 'buttonStyle',
      component: 'Select',
      componentProps: {
        options: [
          { label: 'Link', value: 'link' },
          { label: 'Button', value: 'button' },
          { label: 'Form', value: 'form' },
        ],
      },
      defaultValue: 'link',
    },
    {
      label: '按钮位置',
      field: 'optPosition',
      component: 'Select',
      componentProps: {
        options: [
          { label: '侧面', value: '1' },
          { label: '底部', value: '2' },
        ],
      },
      defaultValue: '2',
      show: ({ model }) => model.buttonStyle === 'form',
    },
    {
      label: '按钮类型',
      field: 'optType',
      component: 'Select',
      componentProps: {
        options: [
          { label: 'Js', value: 'js' },
          { label: 'Action', value: 'action' },
        ],
      },
      defaultValue: 'js',
    },
    {
      label: '排序',
      field: 'orderNum',
      component: 'InputNumber',
      componentProps: {
        style: 'width: 100%',
      },
    },
    {
      label: '按钮图标',
      field: 'buttonIcon',
      component: 'Input',
      helpMessage: 'a-icon type',
    },
    {
      label: '表达式',
      field: 'exp',
      component: 'Input',
    },
    {
      label: '按钮状态',
      field: 'buttonStatus',
      component: 'RadioButtonGroup',
      componentProps: {
        options: [
          { label: '激活', value: '1' },
          { label: '未激活', value: '0' },
        ],
      },
      defaultValue: '1',
    },
  ];

  export default defineComponent({
    name: 'CustomButtonList',
    components: { BasicModal, BasicTable, TableAction, BasicForm },
    emits: ['register'],
    setup() {
      const code = ref('');
      const { doRequest, doDeleteRecord, tableContext } = useListPage({
        tableProps: {
          api: (params) => list(code.value, params),
          columns,
          canResize: false,
          useSearchForm: false,
          beforeFetch(params) {
            return Object.assign(params, { column: 'orderNum', order: 'asc' });
          },
        },
      });
      const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
      const [registerModal, { closeModal }] = useModalInner(async (data) => {
        code.value = data.row.id;
        reload();
      });
      const { aiTestMode, genButtons } = useOnlineTest();
      const [registerFormModal, formModal] = useModal();
      const isUpdate = ref(false);
      const formModalProps = reactive({
        onRegister: registerFormModal,
        title: computed(() => ((isUpdate.value == null ? void 0 : isUpdate.value) ? '修改' : '新增')),
        width: 800,
        confirmLoading: false,
        onOk: onSubmit,
        onCancel: formModal.closeModal,
      });
      let formRecord = {};
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        schemas: formSchemas,
        showActionButtonGroup: false,
      });
      async function openFormModal(data) {
        var _a;
        isUpdate.value = data.isUpdate;
        formRecord = Object.assign({}, (_a = data.record) != null ? _a : {});
        formModal.openModal();
        await nextTick();
        await resetFields();
        setFieldsValue(formRecord);
      }
      function onAdd() {
        openFormModal({ isUpdate: false });
      }
      function onEdit(record) {
        openFormModal({ isUpdate: true, record });
      }
      function onCancel() {
        closeModal();
      }
      function onGenButtons() {
        genButtons(code.value);
      }
      async function onBatchDelete() {
        doRequest(() => doBatchDelete(selectedRowKeys.value));
      }
      async function onSubmit() {
        try {
          formModalProps.confirmLoading = true;
          let values = await validate();
          values = Object.assign({ cgformHeadId: code.value }, formRecord, values);
          await saveOrUpdate(values, isUpdate.value);
          reload();
          formModal.closeModal();
        } finally {
          formModalProps.confirmLoading = false;
        }
      }
      function getTableAction(record) {
        return [
          {
            label: '编辑',
            onClick: () => onEdit(record),
          },
        ];
      }
      function getDropDownAction(record) {
        return [
          {
            label: '删除',
            popConfirm: {
              title: '确定删除吗？',
              placement: 'left',
              confirm: () => doDeleteRecord(() => doBatchDelete([record.id])),
            },
          },
        ];
      }
      return {
        onAdd,
        onBatchDelete,
        aiTestMode,
        onGenButtons,
        registerModal,
        registerTable,
        selectedRowKeys,
        rowSelection,
        onCancel,
        getTableAction,
        getDropDownAction,
        registerForm,
        formModalProps,
      };
    },
  });
</script>
<style scoped></style>
